package nio.base;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class FileChannelTest {

    public static void main(String[] args) throws IOException {

        RandomAccessFile file = new RandomAccessFile("read.txt", "rw");
        FileChannel channel = file.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(48);
        int readCount = channel.read(buf);
        while (readCount != -1) {

            System.out.print("Read " + readCount + "：");
            buf.flip(); //切换为读模式
//			buf.position(0); //这种也可以切换为读模式，好像没有flip安全，要把握好

            CharBuffer charBuffer = Charset.forName("utf-8").newDecoder().decode(buf);
            System.out.println(charBuffer.toString());
//			while(buf.hasRemaining()){
//				System.out.print("--" + buf.get());
//			}
            buf.clear();  //clear、compact、rewind可以切换为写模式
            readCount = channel.read(buf);
        }
        file.close();
    }
}
